package com.guapi.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.guapi.dao.User;
import com.guapi.security.UserDetailImpl;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetailImpl userDetail = (UserDetailImpl) authentication.getPrincipal();
        List<String> permissions = userDetail.getPermissions();
        User user = userDetail.getUser();
        Authentication token = new UsernamePasswordAuthenticationToken(user.getAccount(), user.getPassword());
        SecurityContextHolder.getContext().setAuthentication(token);

        //直接输出json格式的响应信息
        Object principal = authentication.getPrincipal();
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        //以json格式对外输出身份信息
        out.write(new ObjectMapper().writeValueAsString(principal));
        out.flush();
        out.close();

    }
}
